using System;
using System.Collections.Generic;
using System.Reflection;
using System.Reflection.Emit;
using HarmonyLib;

namespace TheWorldOfKongfuEasyMod;

[HarmonyPatch(typeof(CreateWGController))]
[HarmonyPatch(MethodType.Constructor)]
public static class Patch_CreateWGController_LeveLimit
{
    public static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions, ILGenerator generator)
    {
        var codeMatcher = new CodeMatcher(instructions, generator);
        
        codeMatcher.MatchForward(false, new CodeMatch(OpCodes.Stfld, typeof(CreateWGController)
            .GetField("levelLimit", BindingFlags.Instance| BindingFlags.Public | BindingFlags.NonPublic))
        );
        if (!codeMatcher.IsValid)
        {
            throw new InvalidOperationException("Can't find PackageController.UpdatePackageItemDetail");
        }

        codeMatcher.Advance(-1);
        codeMatcher.RemoveInstruction()
            .InsertAndAdvance(
                new CodeInstruction(OpCodes.Ldc_I4_S,Main.Setting._008createWuGongLevelLimit.Value)
            );
        return codeMatcher.Instructions();
    }
}